<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品类型" prop="type">
        <el-cascader
          v-model="queryParams.type"
          :options="typeTreeData"
          :props="{
            checkStrictly: true,
            value: 'id',
            label: 'name',
            children: 'children',
            emitPath: false,
            expandTrigger: 'hover'
          }"
          placeholder="请选择商品类型"
          clearable
          filterable
        ></el-cascader>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-time"
          size="mini"
          @click="handleAuditStatus(2)"
          :class="{ 'is-active': queryParams.status === 2 }"
        >未审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-check"
          size="mini"
          @click="handleAuditStatus(1)"
          :class="{ 'is-active': queryParams.status === 1 }"
        >已审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['supply:prodinfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productListList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品详情" align="center">
        <template slot-scope="scope">
          <!--          <el-button-->
          <!--            type="text"-->
          <!--            icon="el-icon-edit"-->
          <!--            @click="getInfo(scope.row)"-->
          <!--            v-hasPermi="['supply:prodinfo:list']"-->
          <!--          >查看</el-button>-->
          <el-button @click="getInfo(scope.row)" type="primary" v-hasPermi="['supply:prodinfo:list']">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column label="主键商品ID" align="center" prop="id" />
      <el-table-column label="商品名称" align="center" prop="name" />
      <el-table-column label="商品图片" align="center" prop="imageUrl" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.imageUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="商品类型" align="center" prop="type">
        <template slot-scope="scope">
          <span>{{ getTypeName(scope.row.type) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品品牌" align="center" prop="brand" />
      <el-table-column label="最小单位" align="center" prop="minUnit" />
      <el-table-column label="商品性质" align="center" prop="nature" />
      <el-table-column label="供应商" align="center" prop="supplierName" />
      <el-table-column label="库存数量" align="center" prop="stockQuantity" />
      <el-table-column label="单价" align="center" prop="unitPrice" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.product_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="StatusUpdate(scope.row,1)"
            v-hasPermi="['supply:prodinfo:edit']"
          >通过</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="StatusUpdate(scope.row,3)"
            v-hasPermi="['supply:prodinfo:remove']"
          >驳回</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品列表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body custom-class="product-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="product-form">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="商品名称" prop="name" class="is-required">
                  <el-input
                    v-model="form.name"
                    placeholder="商品名称"
                    prefix-icon="el-icon-goods"
                    readonly
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="商品图片" prop="imageUrl" class="upload-item is-required">
                  <image-preview :src="form.imageUrl" :width="150" :height="150"/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="商品多图" prop="imageList" class="upload-item">
                  <div v-if="form.imageList && form.imageList.length > 0" class="image-list">
                    <image-preview
                      v-for="(img, index) in form.imageList"
                      :key="index"
                      :src="img"
                      :width="100"
                      :height="100"
                      class="multi-image"
                    />
                  </div>
                  <div class="upload-tip" v-else>无商品轮播图</div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品类型" prop="type" class="is-required">
                  <el-input v-model="typeNameText" readonly />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品品牌" prop="brand">
                  <el-input
                    v-model="form.brand"
                    prefix-icon="el-icon-collection-tag"
                    readonly
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="最小单位" prop="minUnit">
                  <el-input
                    v-model="form.minUnit"
                    prefix-icon="el-icon-box"
                    readonly
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品性质" prop="nature">
                  <el-input
                    v-model="form.nature"
                    prefix-icon="el-icon-info"
                    readonly
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="供应商" prop="supplierName">
                  <el-input
                    v-model="form.supplierName"
                    prefix-icon="el-icon-user"
                    readonly
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="仓库" prop="warehouseName">
                  <el-input
                    v-model="form.warehouseName"
                    prefix-icon="el-icon-user"
                    readonly
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="库存数量" prop="stockQuantity">
                  <el-input
                    v-model="form.stockQuantity"
                    prefix-icon="el-icon-tickets"
                    readonly
                  >
                    <template slot="append">件</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="单价" prop="unitPrice">
                  <el-input
                    v-model="form.unitPrice"
                    prefix-icon="el-icon-money"
                    readonly
                  >
                    <template slot="prepend">¥</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input
                    v-model="form.remark"
                    type="textarea"
                    :rows="3"
                    resize="none"
                    readonly
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="商品详情图片" name="details">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="商品介绍图" prop="prodIntroduceImgUrls" class="upload-item">
                  <div v-if="form.prodIntroduceImgUrls" class="image-list">
                    <image-preview
                      v-for="(img, index) in getImageArray(form.prodIntroduceImgUrls)"
                      :key="index"
                      :src="img"
                      :width="120"
                      :height="120"
                      class="multi-image"
                    />
                  </div>
                  <div class="upload-tip" v-else>无商品介绍图片</div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="商品参数图" prop="prodParamImgUrls" class="upload-item">
                  <div v-if="form.prodParamImgUrls" class="image-list">
                    <image-preview
                      v-for="(img, index) in getImageArray(form.prodParamImgUrls)"
                      :key="index"
                      :src="img"
                      :width="120"
                      :height="120"
                      class="multi-image"
                    />
                  </div>
                  <div class="upload-tip" v-else>无商品参数图片</div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="商品详细图" prop="prodDetailImgUrls" class="upload-item">
                  <div v-if="form.prodDetailImgUrls" class="image-list">
                    <image-preview
                      v-for="(img, index) in getImageArray(form.prodDetailImgUrls)"
                      :key="index"
                      :src="img"
                      :width="120"
                      :height="120"
                      class="multi-image"
                    />
                  </div>
                  <div class="upload-tip" v-else>无商品详细图片</div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="商品应用图" prop="prodApplyImgUrls" class="upload-item">
                  <div v-if="form.prodApplyImgUrls" class="image-list">
                    <image-preview
                      v-for="(img, index) in getImageArray(form.prodApplyImgUrls)"
                      :key="index"
                      :src="img"
                      :width="120"
                      :height="120"
                      class="multi-image"
                    />
                  </div>
                  <div class="upload-tip" v-else>无商品应用场景图片</div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel" plain>
          <i class="el-icon-close"></i>
          取 消
        </el-button>
        <el-button
          type="success"
          plain
          @click="StatusUpdate(form, 1)"
          v-hasPermi="['supply:prodinfo:edit']"
        >
          <i class="el-icon-check"></i>
          通 过
        </el-button>
        <el-button
          type="danger"
          plain
          @click="StatusUpdate(form, 3)"
          v-hasPermi="['supply:prodinfo:remove']"
        >
          <i class="el-icon-close"></i>
          驳 回
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {AlreadyListProdInfo,listProdinfo, getProdinfo, updateProdinfo, getProdinfoPro} from "@/api/supply/prodinfo";
import { fetchCategoryTree } from "@/api/official";

export default {
  name: "ProductList",
  dicts: ['product_type', 'product_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品列表表格数据
      productListList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 当前活动的标签页
      activeTab: 'basic',
      // 商品类型树数据
      typeTreeData: [],
      // 提取的所有类型列表
      thirdLevelTypes: [],
      // 类型名称文本
      typeNameText: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        type: null,
        status: 2  // 默认显示未审核状态
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "商品类型不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.initTypeTreeData();
  },
  methods: {
    /** 初始化类型树数据 */
    initTypeTreeData() {
      // 从API获取商品类型树
      fetchCategoryTree().then(response => {
        console.log('TypeTree API响应:', response);

        try {
          // 获取API返回的数据
          const rawData = response.data || response;

          // 使用专门的处理函数处理TypeTree格式的数据
          const processedTypeTree = this.processTypeTreeData(rawData);

          // 如果成功处理出数据，则更新本地数据
          if (processedTypeTree && processedTypeTree.length > 0) {
            this.typeTreeData = processedTypeTree;
            console.log('使用API返回的类型数据:', this.typeTreeData);

            // 更新分类列表
            this.extractThirdLevelTypes(this.typeTreeData);
          }
        } catch (error) {
          console.error('处理API返回数据出错:', error);
        }
      }).catch(error => {
        console.error('调用TypeTree API失败:', error);
      });
    },
    /** 提取所有类型 */
    extractThirdLevelTypes(treeData) {
      this.thirdLevelTypes = [];

      if (!treeData || treeData.length === 0) return;

      // 递归提取所有层级的类型
      const extractAllLevels = (nodes, parentPath = '') => {
        if (!nodes || !Array.isArray(nodes)) return;

        nodes.forEach(node => {
          if (!node) return;

          const id = typeof node.id === 'string' ? parseInt(node.id, 10) : (node.id || 0);
          const name = node.name || node.label || '未命名类型';
          const fullPath = parentPath ? `${parentPath} > ${name}` : name;

          // 添加当前节点到类型列表
          this.thirdLevelTypes.push({
            id: id,
            name: name,
            fullPath: fullPath
          });

          // 递归处理子节点
          if (node.children && node.children.length > 0) {
            extractAllLevels(node.children, fullPath);
          }
        });
      };

      // 开始递归处理
      extractAllLevels(treeData);
    },
    /** 处理类型树数据 */
    processTypeTreeData(rawData) {
      console.log('处理TypeTree数据', rawData);

      // 检查数据是否有效
      if (!rawData || !Array.isArray(rawData) || rawData.length === 0) {
        console.log('无有效类型数据');
        return null;
      }

      // 创建处理结果数组 - 存储一级类目
      let processedData = [];

      // 遍历每一个一级类目项
      rawData.forEach(item => {
        if (!item || !item.firstCatalog) return;

        // 获取一级类目信息
        const firstCatalog = item.firstCatalog;

        // 创建一级类目节点
        const level1Node = {
          id: firstCatalog.id,
          name: firstCatalog.name,
          children: []
        };

        // 处理二级类目 - 来自childrenCatalog数组
        if (item.childrenCatalog && Array.isArray(item.childrenCatalog)) {
          // 只处理与当前一级类目关联的二级类目
          const level2Items = item.childrenCatalog.filter(l2 =>
            l2.parentId === firstCatalog.id ||
            l2.level === 2
          );

          level2Items.forEach(level2Item => {
            // 创建二级类目节点
            const level2Node = {
              id: level2Item.id,
              name: level2Item.name,
              children: []
            };

            // 处理三级类目 - 通常在二级类目的children中
            if (level2Item.children && Array.isArray(level2Item.children)) {
              // 筛选出确实是三级的项目
              const level3Items = level2Item.children.filter(l3 =>
                l3.parentId === level2Item.id ||
                l3.level === 3
              );

              level3Items.forEach(level3Item => {
                // 添加三级类目节点
                level2Node.children.push({
                  id: level3Item.id,
                  name: level3Item.name
                });
              });
            }

            // 只有当有三级节点时才保留children属性
            if (level2Node.children.length === 0) {
              delete level2Node.children;
            }

            // 添加二级节点到一级节点的children中
            level1Node.children.push(level2Node);
          });
        }

        // 只有当有二级节点时才保留children属性
        if (level1Node.children.length === 0) {
          delete level1Node.children;
        }

        // 添加一级节点到结果数组
        processedData.push(level1Node);
      });

      return processedData.length > 0 ? processedData : null;
    },
    /** 获取类型名称 */
    getTypeName(typeId) {
      if (typeId === undefined || typeId === null) return '未知类型';

      // 检查原始ID并转换为数字和字符串形式，便于多种匹配
      const typeStr = String(typeId);
      let typeNum = Number(typeId);
      if (isNaN(typeNum)) typeNum = 0;

      // 定义匹配方法，按优先级尝试不同匹配策略
      const matchingType = this.thirdLevelTypes.find(t =>
        t.id === typeId ||             // 完全匹配(保持原始类型)
        t.id === typeNum ||            // 数字类型匹配
        String(t.id) === typeStr       // 字符串匹配
      );

      // 如果找到匹配，返回类型名称
      if (matchingType) {
        return matchingType.name;
      }

      // 如果没有匹配，首先尝试从字典中获取
      const dictType = this.dict.type.product_type.find(d =>
        d.value === typeId ||
        d.value === typeNum ||
        d.value === typeStr
      );

      if (dictType) {
        return dictType.label;
      }

      // 最后返回默认值
      return `商品类型(${typeId})`;
    },
    /** 将逗号分隔的图片URL字符串转为数组 */
    getImageArray(imageUrls) {
      if (!imageUrls) return [];
      if (Array.isArray(imageUrls)) return imageUrls;
      return imageUrls.split(',').filter(url => url && url.trim() !== '');
    },
    /** 查询商品列表列表 */
    getList() {
      this.loading = true;
      // 创建一个新的查询参数对象
      const params = {
        ...this.queryParams
      };

      // 根据状态调用不同的接口
      if (this.queryParams.status === 2) {
        // 未审核状态，调用ListProdInfo接口，只发送status参数
        listProdinfo({
          pageNum: params.pageNum,
          pageSize: params.pageSize,
          name: params.name,
          type: params.type,
          status: 2
        }).then(response => {
          this.productListList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      } else {
        // 已审核状态，调用AlreadyListProdInfo接口，只发送statusList参数
        AlreadyListProdInfo({
          pageNum: params.pageNum,
          pageSize: params.pageSize,
          name: params.name,
          type: params.type,
          statusList: [0,1,3]
        }).then(response => {
          this.productListList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        imageUrl: null,
        imageList: [],
        type: null,
        brand: null,
        minUnit: null,
        nature: null,
        supplierId: null,
        stockQuantity: null,
        unitPrice: null,
        remark: null,
        status: null,
        prodIntroduceImgUrls: '',
        prodParamImgUrls: '',
        prodDetailImgUrls: '',
        prodApplyImgUrls: ''
      };
      this.typeNameText = "";
      this.activeTab = 'basic';
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    //信息查看
    getInfo(row) {
      this.reset();
      const id = row.id
      getProdinfoPro(id).then(response => {
        this.form = response.data;

        // 处理图片列表
        if (this.form.imageUrl && this.form.imageUrl.includes(',')) {
          this.form.imageList = this.form.imageUrl.split(',');
          this.form.imageUrl = this.form.imageList[0]; // 首张图片作为主图
        } else if (this.form.imageUrl) {
          this.form.imageList = [this.form.imageUrl];
        } else {
          this.form.imageList = [];
        }

        // 设置类型名称
        this.typeNameText = this.getTypeName(this.form.type);

        this.open = true;
        this.title = "商品信息";
      });
    },
    /** 修改状态 */
    StatusUpdate(row, status) {
      const id = row.id || (this.form && this.form.id);
      if (!id) {
        this.$modal.msgError("未找到商品ID");
        return;
      }

      const statusText = status === 1 ? '通过' : '驳回';
      this.$modal.confirm('确认要' + statusText + '商品编号为"' + id + '"的商品吗？').then(function() {
        return updateProdinfo({ id: id, status: status });
      }).then(() => {
        this.getList();
        this.open = false;
        this.$modal.msgSuccess(statusText + "成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('supply/prodinfo/export', {
        ...this.queryParams
      }, `商品审核列表_${new Date().getTime()}.xlsx`)
    },
    /** 处理审核状态切换 */
    handleAuditStatus(status) {
      if (status === 2) {
        // 未审核状态
        this.queryParams.status = 2;
      } else {
        // 已审核状态
        this.queryParams.status = '1,2,3';
      }
      this.getList();
    }
  }
};
</script>

<style lang="scss" scoped>
.el-cascader {
  width: 100%;
}

.mb8 {
  margin-bottom: 8px;

  .el-button {
    &.is-active {
      color: #fff;
      border-color: transparent;

      &.el-button--primary {
        background-color: #409EFF;
      }

      &.el-button--success {
        background-color: #67C23A;
      }
    }
  }
}

.product-dialog {
  ::v-deep .el-dialog__body {
    padding: 20px 30px;
  }

  .product-form {
    .el-form-item {
      margin-bottom: 22px;

      &.is-required .el-form-item__label:before {
        color: #f56c6c;
      }

      &.upload-item {
        .image-list {
          display: flex;
          flex-wrap: wrap;
          gap: 10px;

          .multi-image {
            margin-right: 10px;
            margin-bottom: 10px;
          }
        }

        .upload-tip {
          font-size: 12px;
          color: #909399;
          margin-top: 8px;
          line-height: 1.4;
        }
      }

      .el-input {
        .el-input__inner {
          height: 36px;
          line-height: 36px;
        }

        .el-input-group__prepend,
        .el-input-group__append {
          background-color: #f5f7fa;
          color: #909399;
          border-color: #dcdfe6;
        }
      }

      .el-textarea__inner {
        padding: 8px 12px;
        min-height: 80px;
      }
    }
  }

  .dialog-footer {
    text-align: right;
    padding-top: 20px;
    border-top: 1px solid #e4e7ed;

    .el-button {
      padding: 9px 20px;
      font-size: 14px;
      border-radius: 4px;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);
      }

      i {
        margin-right: 5px;
        font-size: 14px;
      }
    }
  }
}

/* 标签样式 */
::v-deep .el-tabs__item {
  font-size: 14px;
  height: 40px;
  line-height: 40px;
}

::v-deep .el-tabs__nav-wrap::after {
  height: 1px;
}

::v-deep .el-tabs__active-bar {
  height: 2px;
}
</style>
